package com.tsfyun.scm.support;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.tsfyun.common.base.constant.LoginConstant;
import com.tsfyun.common.base.dto.Result;
import com.tsfyun.common.base.enums.core.DeviceEnum;
import com.tsfyun.common.base.exception.ServiceException;
import com.tsfyun.common.base.util.DeviceUtil;
import com.tsfyun.common.base.util.StringUtils;
import com.tsfyun.common.base.util.TsfPreconditions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @CreateDate: Created in 2020/9/23 09:52
 */
@Slf4j
@RefreshScope
@Component
public class LoginHelper {

    @Value("${auth.expireSecond:3600}")
    private long pcTokenExpireTime;

    @Value("${auth.client.expireDays}")
    private int clientExpireDays;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //获取accessToken
    private static final String accessTokenUrl = "https://www.xxxx.com/scm/auth/getAccessToken";

    /**
     * 根据终端类型获取失效时间
     * @return
     */
    public long loginExpireTime() {
        long tokenExpireTime = 0l;
        DeviceEnum deviceEnum = DeviceUtil.getPlatform();
        //根据平台类型来确定登录失效时间，暂只有PC端采用30分钟失效可以续签，其他的终端3天有效凌晨3点失效不续签
        if(Objects.equals(deviceEnum,DeviceEnum.PC)) {
            tokenExpireTime = pcTokenExpireTime;
        } else {
            long currentTimeMills = System.currentTimeMillis();
            final Calendar calendar = Calendar.getInstance();
            calendar.add(GregorianCalendar.DATE, clientExpireDays);
            calendar.set(Calendar.HOUR_OF_DAY, 7);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            tokenExpireTime = (calendar.getTimeInMillis() - currentTimeMills)/1000;
        }
        return tokenExpireTime;
    }

    /**
     * 获取accessToken
     * @param subjectId
     * @param appKey
     * @param appSecret
     * @return
     */
    public String getScmbotAccessToken(Long subjectId,String appKey,String appSecret) {
        //此处先从缓存中获取accessToken，不存在再调用接口
        String customerAccessToken = stringRedisTemplate.opsForValue().get(LoginConstant.CLIENT_CUSTOMER_ACCESS_TOKEN + subjectId);
        if(StringUtils.isEmpty(customerAccessToken)) {
            log.info("缓存中不存在accessToken，调用获取accessToken");
            String response = HttpRequest.post(accessTokenUrl).form("appkey",appKey).form("appSecret",appSecret)
                    .timeout(3000).execute().body();
            log.info("缓存中不存在accessToken，调用获取accessToken响应【{}】",response);
            TsfPreconditions.checkArgument(StringUtils.isNotEmpty(response),new ServiceException("系统响应异常，请稍后再试"));
            Result result = JSONObject.parseObject(response, Result.class);
            if(!result.isSuccess()) {
                throw new ServiceException(result.getMessage());
            }
            JSONObject dataJSONObject = JSONObject.parseObject(JSONObject.toJSONString(result.getData()));
            customerAccessToken = dataJSONObject.getString("accessToken");
            long expiresIn = dataJSONObject.getLongValue("expiresIn");
            TsfPreconditions.checkArgument(StringUtils.isNotEmpty(customerAccessToken),new ServiceException("获取登录凭证失败，请稍后再试"));
            stringRedisTemplate.opsForValue().set(LoginConstant.CLIENT_CUSTOMER_ACCESS_TOKEN + subjectId,customerAccessToken,expiresIn, TimeUnit.SECONDS);
        }
        return customerAccessToken;
    }

}
